/* $RCSFile: Documents.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Documents/Documents.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:52  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings.PageModules.Documents;
using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Documents
{
    public class DStr
    {    
        #region settings
        
        public const string DOCUMENTS_USE_DEFAULT       =   "DOCUMENTS_USE_DEFAULT";
        public const string DOCUMENTS_PATH              =   "DOCUMENTS_PATH";
        public const string DOCUMENTS_SHOWIMAGES        =   "DOCUMENTS_SHOWIMAGES";
        public const string DOCUMENTS_DBSAVE            =   "DOCUMENTS_DBSAVE";
        public const string DOCUMENTS_SORTBY_FIELD      =   "DOCUMENTS_SORTBY_FIELD";
        public const string DOCUMENTS_SORTBY_DIRECTION  =   "DOCUMENTS_SORTBY_DIRECTION";
        public const string DOCUMENTS_SHOWTITLE         =   "DOCUMENTS_SHOWTITLE";
        public const string DOCUMENTS_SHOWOWNER         =   "DOCUMENTS_SHOWOWNER";
        public const string DOCUMENTS_SHOWAREA          =   "DOCUMENTS_SHOWAREA";
        public const string DOCUMENTS_SHOWLASTUPDATED   =   "DOCUMENTS_SHOWLASTUPDATED";
        public const string DOCUMENTS_INCLUDECRMPRODUCTS=   "DOCUMENTS_INCLUDECRMPRODUCTS";
        public const string DOCUMENTS_ONLYCUSTOMERVIEW  =   "DOCUMENTS_ONLYCUSTOMERVIEWABLE";
        public const string DOCUMENTS_NEWAPI            =   "DOCUMENTS_NEWAPI";
    
        #endregion settings

        #region resource strings

        public const string DOCUMENTS_SORTBY_FIELD_LIST     =   "DOCUMENTS_SORTBY_FIELD_LIST";
        public const string DOCUMENTS_SORTBY_DIRECTION_LIST =   "DOCUMENTS_SORTBY_DIRECTION_LIST";
        public const string ERROR_FILE_DELETE               =   "ERROR_FILE_DELETE";
        public const string ERROR_FILE_NAME                 =   "ERROR_FILE_NAME";
        public const string CREATED_BY                      =   "CREATED_BY"; 
        public const string ON                              =   "ON";
        public const string DOCUMENT_DETAILS                =   "DOCUMENT_DETAILS";
        public const string FILE_NAME                       =   "FILE_NAME";
        public const string CATEGORY                        =   "CATEGORY";
        public const string URL                             =   "URL";
        public const string UPLOAD_FILE                     =   "UPLOAD_FILE";
        public const string OR                              =   "OR";
        public const string VALID_FILE_NAME                 =   "VALID_FILE_NAME";
            
    #endregion resource strings
    }

    /// <summary>
    /// Initializer class for Documents 
    /// </summary>
    public class DocumentsSI : PortalCRMModuleControlSI
    {
        public DocumentsSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DocumentsSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DocumentsSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DocumentsSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                       =   pm.ExtendedResourcesGroup;

            #region Document Setting Items

            SettingItemSpecial UseDefaultPath   =   new SettingItemSpecial(DStr.DOCUMENTS_USE_DEFAULT,new BooleanDataType());
            UseDefaultPath.Value                =   StStr.strTrue;
            UseDefaultPath.Order                =   1;
            UseDefaultPath.ExtendedGroupName    =   extgrp;
            UseDefaultPath.EnglishName          =   "Use Default Portal Path";
            UseDefaultPath.Description          =   "Take the path set in Site Settings as default Document repository";
            bSettings.AddSetting(UseDefaultPath);

            SettingItemSpecial DocumentPath     =   new SettingItemSpecial(DStr.DOCUMENTS_PATH,new PortalUrlDataType());
            DocumentPath.Required               =   true;
            DocumentPath.Value                  =   StStr.DocumentsBaseFolderName;
            DocumentPath.Order                  =   10;
            DocumentPath.ExtendedGroupName      =   extgrp;
            DocumentPath.EnglishName            =   "Document path";
            DocumentPath.Description            =   "Folder for storing documents";
            bSettings.AddSetting(DocumentPath);

            SettingItemSpecial ShowImages       =   new SettingItemSpecial(DStr.DOCUMENTS_SHOWIMAGES,new BooleanDataType());
            ShowImages.Value                    =   StStr.strTrue;
            ShowImages.Order                    =   20;
            ShowImages.ExtendedGroupName        =   extgrp;
            ShowImages.EnglishName              =   " Show Image Icons?";
            ShowImages.Description              =   " Mark this if you like see Image Icons";
            bSettings.AddSetting(ShowImages);

            SettingItemSpecial SaveInDataBase   =   new SettingItemSpecial(DStr.DOCUMENTS_DBSAVE,new BooleanDataType());
            SaveInDataBase.Value                =   StStr.strFalse;
            SaveInDataBase.Order                =   30;
            SaveInDataBase.ExtendedGroupName    =   extgrp;
            SaveInDataBase.EnglishName          =   "Save files in DataBase only";
            SaveInDataBase.Description          =   "When checked, files will not be saved on disk, always in DB";
            bSettings.AddSetting(SaveInDataBase);

            string sortflds                     =   LocalizeHelper.Localize(DStr.DOCUMENTS_SORTBY_FIELD_LIST,"File Name;Created By;Category;Created Date");
            string[] sortfld                    =   sortflds.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            ArrayList sortfldlst                =   new ArrayList();

            
            if ( sortfld.Length == 4 )
            {
                ListItem it                     =   new ListItem(sortfld[0],"FileFriendlyName");
                sortfldlst.Add(it);
                it                              =   new ListItem(sortfld[1],"CreatedByUser");
                sortfldlst.Add(it);
                it                              =   new ListItem(sortfld[2],"Category");
                sortfldlst.Add(it);
                it                              =   new ListItem(sortfld[2],"CreatedDate");
                sortfldlst.Add(it);
            }
            else
            {
                ListItem it                     =   new ListItem("File Name","FileFriendlyName");
                sortfldlst.Add(it);
                it                              =   new ListItem("Created By","CreatedByUser");
                sortfldlst.Add(it);
                it                              =   new ListItem("Category","Category");
                sortfldlst.Add(it);
                it                              =   new ListItem("Created Date","CreatedDate");
                sortfldlst.Add(it);
            }

            SettingItemSpecial SortByField      =   new SettingItemSpecial(DStr.DOCUMENTS_SORTBY_FIELD,new CustomListDataType(sortfldlst,"Text","Value"));
            SortByField.Required                =   true;
            SortByField.Value                   =   "FileFriendlyName";
            SortByField.Order                   =   40;
            SortByField.ExtendedGroupName       =   extgrp;
            SortByField.EnglishName             =   "Sort Field?";
            SortByField.Description             =   "Sort by File Name or by Created Date?";
            bSettings.AddSetting(SortByField);

            string sortitems                    =   LocalizeHelper.Localize(DStr.DOCUMENTS_SORTBY_DIRECTION_LIST,"Ascending;Descending");
            string[] sortitem                   =   sortitems.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            
            ArrayList sortlst                   =   new ArrayList();
            if ( sortitem.Length == 2 )
            {
                ListItem it                     =   new ListItem(sortitem[0],"ASC");
                sortlst.Add(it);
                it                              =   new ListItem(sortitem[1],"DESC");
            }
            else
            {
                ListItem it                     =   new ListItem("Ascending","ASC");
                sortlst.Add(it);
                it                              =   new ListItem("Descending","DESC");
            }


            SettingItemSpecial SortByDirection  =   new SettingItemSpecial(DStr.DOCUMENTS_SORTBY_DIRECTION,new CustomListDataType(sortlst,"Text","Value"));
            SortByDirection.Value               =   "ASC";
            SortByDirection.Order               =   50;
            SortByDirection.ExtendedGroupName   =   extgrp;
            SortByDirection.EnglishName         =   "Sort ascending or descending?";
            SortByDirection.Description         =   "Ascending: A to Z or 0 - 9. Descending: Z - A or 9 - 0.";
            bSettings.AddSetting(SortByDirection);


            SettingItemSpecial showTitle        =   new SettingItemSpecial(DStr.DOCUMENTS_SHOWTITLE,new BooleanDataType());
            showTitle.Value                     =   StStr.strTrue;
            showTitle.Order                     =   60;
            showTitle.ExtendedGroupName         =   extgrp;
            showTitle.EnglishName               =   "Show Title column?";
            showTitle.Description               =   "Mark this if the title column should be displayed";
            bSettings.AddSetting(showTitle);

            SettingItemSpecial showOwner        =   new SettingItemSpecial(DStr.DOCUMENTS_SHOWOWNER,new BooleanDataType());
            showOwner.Value                     =   StStr.strTrue;
            showOwner.Order                     =   70;
            showTitle.ExtendedGroupName         =    extgrp;
            showOwner.EnglishName               =   "Show Owner column?";
            showOwner.Description               =   "Mark this if the owner column should be displayed";
            bSettings.AddSetting(showOwner);

            SettingItemSpecial showArea         =   new SettingItemSpecial(DStr.DOCUMENTS_SHOWAREA,new BooleanDataType());
            showArea.Value                      =   StStr.strTrue;
            showArea.Order                      =   80;
            showArea.ExtendedGroupName          =   extgrp;
            showArea.EnglishName                =   "Show Area column";
            showArea.Description                =   "Mark this if the area column should be displayed";
            bSettings.AddSetting(showArea);

            SettingItemSpecial showLastUpdated  =   new SettingItemSpecial(DStr.DOCUMENTS_SHOWLASTUPDATED,new BooleanDataType());
            showLastUpdated.Value               =   StStr.strTrue;
            showLastUpdated.Order               =   90;
            showLastUpdated.ExtendedGroupName   =   extgrp;
            showLastUpdated.EnglishName         =   "Show Last Updated column";
            showLastUpdated.Description         =   "Mark this if the Last Updated column should be displayed";
            bSettings.AddSetting(showLastUpdated);

            SettingItemSpecial includeCrmDoc    =   new SettingItemSpecial(DStr.DOCUMENTS_INCLUDECRMPRODUCTS,new BooleanDataType());
            includeCrmDoc.Value                 =   StStr.strFalse;
            includeCrmDoc.Order                 =   100;
            includeCrmDoc.ExtendedGroupName     =   extgrp;
            includeCrmDoc.EnglishName           =   "Crm sales Documentation";
            includeCrmDoc.Description           =   "Check to include Crm sales documentation";
            bSettings.AddSetting(includeCrmDoc);
            
            SettingItemSpecial onlyCustomerView =   new SettingItemSpecial(DStr.DOCUMENTS_ONLYCUSTOMERVIEW,new BooleanDataType());
            onlyCustomerView.Value              =   StStr.strTrue;
            onlyCustomerView.Order              =   110;
            onlyCustomerView.ExtendedGroupName  =   extgrp;
            onlyCustomerView.EnglishName        =   "Only Customer Viewable";
            onlyCustomerView.Description        =   "Include only Crm documents marked as customer viewable";
            bSettings.AddSetting(onlyCustomerView);

            SettingItemSpecial useNewAPI        =   new SettingItemSpecial(DStr.DOCUMENTS_NEWAPI,new BooleanDataType());
            useNewAPI.Value                     =   StStr.strTrue;
            useNewAPI.Order                     =   120;
            useNewAPI.ExtendedGroupName         =   extgrp;
            useNewAPI.EnglishName               =   "Use Crm4 Rollup7 API";
            useNewAPI.Description               =   "When unchecked use the old CRM3 url loading for content";
            bSettings.AddSetting(useNewAPI);

            #endregion
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DocumentsSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class Documents : PortalCRMModuleControl
    {
        
        DocumentDB docDB                =   new DocumentDB();

        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General Implementation
        public override Guid GuidID
        {
            get
            {
                return new Guid("{F9645B82-CB45-4C4C-BB2D-72FA42FE2B75}");
            }
        }

        #endregion

        public Documents()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Documents Ctor Called.",ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "DOCUMENTS";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new DocumentsSI(bSettings,this);
        }

        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a SqlDataReader of document information from the 
        /// Documents table, and then databind the results to a DataGrid
        /// server control.  It uses the AddonNice.DocumentDB()
        /// data component to encapsulate all data functionality.
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Documents Page_Load BEG.",ModuleTraceSwitch.Sw.Info);
        }
        
        #region Image documents
        
        private void SetImages(DataTable dv)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Documents setDataView begin.",ModuleTraceSwitch.Sw.Info);
            foreach (DataRow dr in dv.Rows)
            {
                //dr["contentType"]   =   imageAssign((string)dr["contentType"]);
                dr["contentType"]   =   DocumentsHelper.GetImage((string)dr["contentType"]);
                
            }
        }

        #endregion

        /// <summary>
        /// GetBrowsePath() is a helper method used to create the url   
        /// to the document.  If the size of the content stored in the   
        /// database is non-zero, it creates a path to browse that.   
        /// Otherwise, the FileNameUrl value is used.
        ///
        /// This method is used in the databinding expression for
        /// the browse Hyperlink within the DataGrid, and is called 
        /// for each row when DataGrid.DataBind() is called.  It is 
        /// defined as a helper method here (as opposed to inline 
        /// within the template) to improve code organization and
        /// avoid embedding logic within the content template.
        /// </summary>
        protected string GetBrowsePath(String url, object size, int documentID,Guid ItemCrmID)
        {
            // if there is content in the database, create an url to browse it
            if ( size != DBNull.Value && ( (int)size ) > 0 )
            {
                // Add ModuleID and itemcrmid into url for correct security access.
                return HttpUrlBuilder.BuildUrl(string.Format("{0}/Documents/DocumentsView.aspx",Config.ModulesPath),string.Format("itemid={0}&itemcrmid={1}&mid={2}",documentID,ItemCrmID,ModuleID));
            }
            // otherwise, return the FileNameUrl
            if ( url.StartsWith("//") ) // special full path entered
                return url;
            if ( url.StartsWith("~") ) // special ~ path entered
                return url.Substring(1);
            bool useDefFolder       =   Settings[DStr.DOCUMENTS_USE_DEFAULT].ToBool();
            string folderVPath      =   string.Empty;
            if ( useDefFolder ) // remap to good folder
                    folderVPath	    =	portalSettings.DefaultDocumentVirtualPath;
			else    folderVPath		=	Settings[DStr.DOCUMENTS_PATH].FullPath;
            return 	AddonNice.Settings.Path.WebPathCombine(folderVPath, url);

        }

        void FillFromCrm(DataTable tb)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Documents FillFromCrm BEG.",ModuleTraceSwitch.Sw.Info);
            SortedList<Guid,ADNDynSalesliteratureitem>  Lst =   ADNDynSalesliteratureitem.ReadAll(Wrapper,ResetWrapper,Settings[DStr.DOCUMENTS_ONLYCUSTOMERVIEW].ToBool());
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Documents FillFromCrm Count: {0}.",Lst.Count),ModuleTraceSwitch.Sw.Info);
            int i                       =  100000;
            foreach ( ADNDynSalesliteratureitem s in Lst.Values )
            {
                ADNDynSalesLiterature p =   s.GetParent(ResetWrapper);
                DataRow rw              =   tb.NewRow();
                rw["ItemID"]            =   i++;
                rw["itemcrmid"]         =   s.salesliteratureitemid;
                rw["FileFriendlyName"]  =   s.title;
                rw["FileNameUrl"]       =   s.attacheddocumenturl;
                rw["CreatedByUser"]     =   s.authorname;
                rw["CreatedDate"]       =   s.createdonUTCDate.ToLocalTime();
                rw["Category"]          =   p.literaturetypecodeLabel;
                rw["ContentSize"]       =   s.filesize;
                int idx                 =   s.filename.LastIndexOf('.');
                if (( idx > -1 ) && ( idx < s.filename.Length ) )
                {
                    string ext          =   s.filename.Substring(idx+1);
                    rw["ContentType"]   =   ext;
                }
                else
                {
                    rw["ContentType"]   =   s.mimetype;
                }
                tb.Rows.Add(rw);
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Documents FillFromCrm END.",ModuleTraceSwitch.Sw.Info);
        }

        void myDataGrid_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Documents myDataGrid_NeedDataSource BEG RebindReason: {0}.",e.RebindReason),ModuleTraceSwitch.Sw.Info);
            try
            {
                DataTable tb            =   docDB.GetDocumentsGlobalizedTb(ModuleID);
                // Add the crmid column
                tb.Columns.Add("itemcrmid",typeof(Guid));
                foreach(DataRow rw in tb.Rows)
                    rw["itemcrmid"]     =   Guid.Empty;
                if ( Settings[DStr.DOCUMENTS_INCLUDECRMPRODUCTS].ToBool() )
                {
                    FillFromCrm(tb);
                }
                SetImages(tb);
                myDataGrid.DataSource   =   tb;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Documents myDataGrid_NeedDataSource ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Documents myDataGrid_NeedDataSource END.",ModuleTraceSwitch.Sw.Info);
        }

        void myDataGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Documents myDataGrid_ItemDataBound BEG ItemType: {0}", e.Item.ItemType),ModuleTraceSwitch.Sw.Info);
            try
            {
               if (e.Item.ItemType != GridItemType.Item     
                    && e.Item.ItemType != GridItemType.AlternatingItem 
                    && e.Item.ItemType != GridItemType.SelectedItem )
                    return;

                Control ctl                         =   e.Item.Cells[1].FindControl("contentType");
                if (ctl is HyperLink)
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Documents myDataGrid_ItemDataBound  SkinId: {0}, NavigateUrl: {1}, ImageUrl: {2}",
                            ((HyperLink)ctl).SkinID,((HyperLink)ctl).NavigateUrl,((HyperLink)ctl).ImageUrl),ModuleTraceSwitch.Sw.Info);
                    if (((HyperLink)ctl).ImageUrl.StartsWith("~"))
                        ((HyperLink)ctl).ImageUrl   =   ((HyperLink)ctl).ImageUrl.Substring(1);
                }
                
                if (e.Item.Cells[3].Text == StStr.unknown)
                    e.Item.Cells[3].Text            =   LocalizeHelper.Localize(StStr.UNKNOWN, StStr.unknown);
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Documents myDataGrid_ItemDataBound ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Documents myDataGrid_ItemDataBound END.",ModuleTraceSwitch.Sw.Info);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Documents Render BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                base.Render(writer);
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Documents Render ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]Documents Render END.",ModuleTraceSwitch.Sw.Info);
        }

        #region Std overrides

        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
            AddText         =   "ADD_DOCUMENT";
            AddUrl          =   Config.ModulesPath + "/Documents/DocumentsEdit.aspx";
            base.Page_PreInit(sender, e);
        }

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            myDataGrid.Columns[0].Visible   =   IsEditable;
            myDataGrid.Columns[1].Visible   =   Settings[DStr.DOCUMENTS_SHOWIMAGES].ToBool();
            myDataGrid.Columns[2].Visible   =   Settings[DStr.DOCUMENTS_SHOWTITLE].ToBool();
            myDataGrid.Columns[3].Visible   =   Settings[DStr.DOCUMENTS_SHOWOWNER].ToBool();
            myDataGrid.Columns[4].Visible   =   Settings[DStr.DOCUMENTS_SHOWAREA].ToBool();
            myDataGrid.Columns[5].Visible   =   Settings[DStr.DOCUMENTS_SHOWLASTUPDATED].ToBool();
            
            GridSortExpression expression = new GridSortExpression();

            string sortFieldOption          =   Settings[DStr.DOCUMENTS_SORTBY_FIELD].ToString();
            string sortDirectionOption      =   Settings[DStr.DOCUMENTS_SORTBY_DIRECTION].ToString();
            if (sortFieldOption.Length > 0)
            {
                if ( sortFieldOption.IndexOf("FileFriendlyName;CreatedByUser;Category;CreatedDate") == -1)
                    expression.FieldName    =   "FileFriendlyName";
                else expression.FieldName   =   sortFieldOption;
                if ( sortDirectionOption.IndexOf("ASC") == -1)
                    expression.SortOrder    =   GridSortOrder.Descending;
                else
                    expression.SortOrder    =   GridSortOrder.Ascending;
            }
            else
            {
                expression.FieldName        =   "FileFriendlyName";
                expression.SortOrder        =   GridSortOrder.Ascending;
            }
            myDataGrid.MasterTableView.SortExpressions.AddSortExpression( expression );

            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                        +=  new EventHandler(Page_Load);
            myDataGrid.NeedDataSource   +=  new GridNeedDataSourceEventHandler(myDataGrid_NeedDataSource);
            myDataGrid.ItemDataBound    +=  new GridItemEventHandler(myDataGrid_ItemDataBound);
        }
        #endregion
    }
}
